﻿using Microsoft.Extensions.DependencyInjection;
using Modules.CheckInCount.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.CheckInCount.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CountPerdayRepository : Repository<CountPerday, CheckinDbContext>
    {
        public CountPerdayRepository(CheckinDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        /// <summary>
        /// 获取指定条件每日统计集合
        /// </summary>
        /// <param name="tenantType"></param>
        /// <param name="countType"></param>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <param name="objectIds"></param>
        /// <returns></returns>
        public IEnumerable<CountPerday> GetCountPerdays(CountTenantType tenantType, CountType countType, int year, int month, int day, IEnumerable<int> objectIds)
        {
            if (objectIds == null || objectIds.Count() == 0)
                return Enumerable.Empty<CountPerday>();

            string tableName = GetTableName(tenantType, countType);
            Sql sql = Sql.Builder;
            sql.Select("*")
                .From(tableName)
                .Where("year=@0 AND month=@1 AND day=@2 AND object_id IN(@3)", year, month, day, objectIds);

            return DbContext.Fetch<CountPerday>(sql);
        }

        /// <summary>
        /// 获取表名
        /// </summary>
        /// <param name="tenantType"></param>
        /// <param name="countType"></param>
        /// <returns></returns>
        private string GetTableName(CountTenantType tenantType, CountType countType)
        {
            return $"{tenantType}_{countType}_perday".ToLower();
        }
    }
}